package com.cheng.learn.sort;

/**
 * @description: 插入排序
 * @author: ChengHaiZhu
 * @create: 2021-03-18 23:09
 **/
public class InsertSort {

    public static void main(String[] args) {
        int[] arr = { 49, 38, 65, 97, 23, 22, 76, 1, 5, 8, 2, 0, -1, 22 , 23};
        insertSort(arr);
        System.out.println("排序后:");
        for (int i : arr) {
            System.out.print(i+" ");
        }
    }

    /**
     * 插入排序，优化后的排序，二分法排序,在找位置的时候利用二分法找合适的位置插入，简单优化
     * @param arr
     */
    public static void insertSort(int[] arr){
        for (int i = 1; i < arr.length; i++) {
            int low = 0;
            int temp = arr[i];
            int high = i - 1;
            while(low <= high){
                int mid = (low + high) / 2;
                if(arr[mid] > temp){
                    high = mid - 1;
                }else{
                    low = mid + 1;
                }
            }
            // 元素依次后移
            for (int j = i; j > low; j--) {
                arr[j] = arr[j - 1];
            }
            arr[low] = temp;
        }
    }
}
